package com.share.wechat.fristpage.service.impl;

import cn.hutool.http.HttpRequest;
import com.share.common.httpclient.util.HttpsClientUtil;
import com.share.common.tools.ID.IDutils;
import com.share.common.tools.collection.CollectionUtil;
import com.share.common.tools.xml.XPathResolveUtil;
import com.share.wechat.fristpage.entity.AnswerEntity;
import com.share.wechat.fristpage.repository.dao.AnswerDao;
import com.share.wechat.fristpage.service.AnswerService;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 玩冲顶大会的小东西
 * Created by er on 2018/1/16.
 */
@Service
public class AnswerServiceImpl implements AnswerService {
    private final Logger logger = Logger.getLogger(this.getClass());
    @Resource
    private AnswerDao answerDao;
    /**
     * 配置信息的集合
     */
    private static Map<String, String> propertiesMap;

    /**
     * 包涵这些词语的就要舍弃掉
     */
    private Map<String, List<String>> dealMap;

    /**
     * 百度搜索的时候的关键字
     */
    private final static String BAI_DU_SEARCH_SKIP_WORD = "bai-du-search-skip-word";//删除句子
    private final static String BAI_DU_SEARCH_DELETE_WORD = "bai-du-search-delete-word";//剔除掉这些词语
    private final static String SURF_ON_TOP = "surfOnTop";//剔除掉这些词语

    /**
     * 配置数据的一部分
     */
    private static Map<String, String> keyMap = new HashMap<>();

    private final Integer MAX_LENGTH_TEXT = 200;
    private final Integer MIN_LENGTH_TEXT = 70;


    static {
        propertiesMap = new HashMap<>();
        keyMap.put("surfOnTop", "chongdingdahui");//冲顶大会的拼音
        keyMap.put("search_on_bai_du_easy", "baidujiandansousuo");//百度简单搜索接口
        keyMap.put("search_on_bai_du_dan_jun", "baidujiandansousuo-danjun");// dan君接口搜索
    }


    /**
     * 该渠道就是从冲顶大会app上渠道数据的
     *
     * @return
     */
    @Override
    public AnswerEntity surfOnTop() {
        return null;
    }

    @Override
    public List<String> search(AnswerEntity entity) {
        /*Map parms = new HashMap(0);
        String parentCode = keyMap.get("search_on_bai_du_easy");
        parms.put("word", entity.getQuestion());
        String searchUrl = this.getUrlByParentCode(parentCode);
        String searchResult = HttpsClientUtil.doPost(searchUrl, parms);//拿到返回的结果
        List<String> returnList = this.getSearch(searchResult);
        return returnList;*/
        return null;
    }

    @Override
    public List<Map<String, List<String>>> searchs(List<String> keyWords) {
        logger.info("开始使用简单搜索在百度上进行搜索");
        logger.info("开始搜索的时候使用的关键字为" + keyWords);
        List<Map<String, List<String>>> returnList = new ArrayList<>(1);
        Map<String, String> htmlMaps = new HashMap<>();
        for (String keyWord : keyWords) {
            Map<String, String> parms = new HashMap<>(6);
            parms.put("word", keyWord);
            parms.put("pd", "wenda_tab");
            parms.put("tn", "vsearch");
            parms.put("sa", "tb");
            parms.put("rsv_sug4", String.valueOf(Math.abs(IDutils.genItemId().shortValue())));
            parms.put("vsearch_change", "1");
            String parentCode = keyMap.get("search_on_bai_du_easy");
            String searchUrl = this.getUrlByParentCode(parentCode);
            String searHtml = HttpsClientUtil.doGet(searchUrl, parms);//拿到返回的结果
            if (logger.isDebugEnabled()) {
                logger.debug("查询请求的参数为" + keyWord);
                logger.debug("从请求返回的html结果为" + searHtml);


            }
            //这部分到底该不该在这里进行处理
            htmlMaps.put(keyWord, searHtml);
        }
        //从后台的页面分析出当前的答案类型
        List<Map<String, List<String>>> mapList = this.elementHtmlToText(htmlMaps);

        if (logger.isDebugEnabled()) {
            logger.debug(mapList);
        }
        return mapList;
    }

    @Override
    public List<Map<String, List<String>>> search(String keyword) {
        List<String> keyWords = new ArrayList<>(1);
        keyWords.add(keyword);
        List<Map<String, List<String>>> mapList = this.searchs(keyWords);
        if (logger.isDebugEnabled()) {
            logger.debug("在搜索的时候 关键词为" + keyword);
            logger.debug("查询的结果为" + mapList);
        }
        return mapList;
    }


    @Override
    public List<Map<String, List<String>>> paseHtml(Map<String, String> htmlMap) {
        List<Map<String, List<String>>> result = new ArrayList<>();
        Map<String, List<String>> skipMaps = this.getDealMap();
        for (String keyWord : htmlMap.keySet()) {
            Map<String, List<String>> addMap = new HashMap<>(1);
            String pathContainer = "//div[@class='c-container']";
            List<String> containers = XPathResolveUtil.paserHtmlToText(pathContainer, htmlMap.get(keyWord));

            logger.info("------------------------------------");

            if (!CollectionUtil.isEmpty(containers)) {
                List<String> addList = new ArrayList<>(0);
                for (String container : containers) {
                    container = container.replaceAll(" ", "");
                    boolean flag = true;
                    if (container.contains("...")) {
                        container = container.substring(0, container.indexOf("..."));
                    }
                    for (String key : skipMaps.keySet()) {
                        if (BAI_DU_SEARCH_SKIP_WORD.equals(key)) {
                            for (String skip : skipMaps.get(key)) {
                                if (container.contains(skip)) {
                                    flag = false;
                                    break;
                                }
                            }
                        } else if (BAI_DU_SEARCH_DELETE_WORD.equals(key)) {
                            for (String delete : skipMaps.get(key)) {
                                if (container.contains(delete)) {
                                    container = container.replaceAll(delete, "");
                                }
                            }
                        }
                    }

                    if (flag) {

                        /*container = container.replaceAll("，", " ");
                        container = container.replaceAll("。", " ");
                        container = container.replaceAll("·", " ");*/
                        // TODO: 2018/1/17  这里应该还是要做很多的事情吧 这里还要进行长度截取
                        if (container.length() > MAX_LENGTH_TEXT) {
                            logger.info(container);
                            if (container.contains(" ")) {
                                container = container.substring(0, container.lastIndexOf(" "));

                            }
                        }
                        container = container.replaceAll(" ", "").trim();
                        if (container.length() > MIN_LENGTH_TEXT) {
                            if (container.contains("。")) {
                                container = container.substring(0, container.lastIndexOf("。"));
                            } else if (container.contains(",")) {
                                container = container.substring(0, container.lastIndexOf(","));
                            } else if (container.contains("，")) {
                                container = container.substring(0, container.lastIndexOf("，"));
                            }

                            addList.add(container.trim());
                            if (logger.isInfoEnabled()) {
                                logger.info("添加一个新的选项" + keyWord + "::::" + container);
                            }
                        }

                    }
                }
                addMap.put(keyWord, addList);
            }

            result.add(addMap);
        }
        return result;
    }


    @Override
    public List<Map<String, List<String>>> elementHtmlToText(Map<String, String> htmlMap) {
        if (logger.isDebugEnabled()) {
            logger.info("开始根据关键词解析文本" + htmlMap);
        }
        List<Map<String, List<String>>> result = new ArrayList<>();
        for (String keyWord : htmlMap.keySet()) {
            Map<String, List<String>> addMap = new HashMap<>(1);
            String pathContainer = "//div[@class='c-container']";
            List<String> answers = new ArrayList<>();
            List<Element> elements = XPathResolveUtil.paserHtmlToElement(pathContainer, htmlMap.get(keyWord));
            if (!CollectionUtil.isEmpty(elements)) {
                for (Element element : elements) {//c-abstract

                    String key = element.select("h3.c-title").text();
                    String answer = element.text();
                    int end = answer.length();
                    if (answer.contains("...")) {
                        end = answer.lastIndexOf("...");
                    }
                    if (end < key.length()) {
                        end = answer.length();
                    }
                    answer = answer.substring(key.length(), end);

                    answers.add(answer);//将答案添加到里边去
                    if (logger.isDebugEnabled()) {
                        logger.debug("key = " + key);
                        logger.debug("answer = " + answer);
                    }
                }
            }
            addMap.put("answer", answers);
            result.add(addMap);
        }
        return result;
    }

    /**
     * 根据返回的结果分析出当前的答案的实体类
     *
     * @param msg 当前的返回的数据
     * @return 答案的实体类
     */
    private AnswerEntity getAnswer(String msg) {
        AnswerEntity entity = new AnswerEntity();
        entity.setQuestion("中国年龄最大的皇帝?");
        List<String> choices = new ArrayList<>(3);
        choices.add("A:秦始皇");
        choices.add("B:汉武帝");
        choices.add("C:武则天");
        entity.setChoices(choices);
        // TODO: 2018/1/16

        return entity;
    }


    @Override
    public String getToSecr(String app) {
        String url = "https://secr.baidu.com/answer";
        String html = "";
        if (StringUtils.isEmpty(app)) {
            logger.warn("未传入接口类型,分类默认为冲顶大会");
            app = propertiesMap.get(SURF_ON_TOP);
        }
        Map<String, String> parms = new HashMap<>();
        parms.put("xc", IDutils.getUUIDNoLine());
        parms.put("app", app);
        html = HttpsClientUtil.doGetIPhone(url, parms);
        //HttpsClientUtil.doGet(url,parms);
        return html;
    }

    /**
     * 从配置信息根据parentCode提取出配置信息
     *
     * @param parentCode parentCode
     * @return 返回的配置信息
     */
    private String getUrlByParentCode(String parentCode) {
        if (propertiesMap.containsValue(parentCode)) {
            return propertiesMap.get(parentCode);
        }
        String urlByParentCode = answerDao.getUrlByParentCode(parentCode);
        propertiesMap.put(parentCode, urlByParentCode);
        return urlByParentCode;
    }

    /**
     * 查询出当前搜索的时候过滤
     * 包含这些句子就直接作废
     *
     * @return 句子集合
     */
    private Map<String, List<String>> getDealMap() {
        if (dealMap == null || dealMap.isEmpty()) {
            dealMap = new HashMap<>(2);
            //拿到删除句子的词组
            dealMap.put(BAI_DU_SEARCH_SKIP_WORD, answerDao.getSkipWord(BAI_DU_SEARCH_SKIP_WORD));
            //拿到要替换词语的词组
            dealMap.put(BAI_DU_SEARCH_DELETE_WORD, answerDao.getSkipWord(BAI_DU_SEARCH_DELETE_WORD));
            if (dealMap.isEmpty()) {
                logger.warn("请检查百度词条解析部分的数据配置信息");
                logger.warn("该地方的数据的解析启用默认的配置信息 也就是没有配置信息");
            }
        }
        return dealMap;
    }

    @Override
    public Map<String, List<String>> searchOnBaiduiEasy(@NotNull String keyWord, @NotNull List<String> choices) {
        Map<String, List<String>> resultMap = new HashMap<>();

        String html = HttpRequest.get("https://www.baidu.com/s?wd=" + keyWord).execute().body();
        if (logger.isDebugEnabled()){
            logger.debug("返回的html代码为" + html);
        }
        String xpath = "//div[@class='c-abstract']";
        List<Element> elements = XPathResolveUtil.paserHtmlToElement(xpath, html);

        if (!CollectionUtil.isEmpty(elements)) {
            List<String> answersList = new ArrayList<>();
            for (Element element : elements) {
                String answer = element.text();
                for (String choice : choices) {
                    if (answer.contains(choice)) {
                        answer = answer.replaceAll(choice, "<font size=\"3\" color=\"red\">" + choice + "</font>");
                    }
                    answersList.add(answer);

                }
            }
            resultMap.put(keyWord, answersList);
        }
        return resultMap;
    }
}




